package com.tanhua.interceptor;

import com.tanhua.commons.JwtUtils;
import com.tanhua.model.User;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*、
* 配置Token拦截器，对每一个请求进行Token的验证，并解析Token的值
* */
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获取token
        String token = request.getHeader("Authorization");
        //对token进行判断
        boolean verifyToken = JwtUtils.verifyToken(token);
        if(!verifyToken){
            //token不同,响应错误编码
            response.setStatus(401);
            return false;
        }
        //解析token，获取里面的id,和电话，因为user表和user-info表进行主键，而且两张表是一一对应的关系
        Claims claims = JwtUtils.getClaims(token);
        Integer id =(Integer) claims.get("id");
        String mobile =(String) claims.get("mobile");
        //将它封装成对象
        User user = new User();
        user.setId(Long.valueOf(id));
        user.setMobile(mobile);
        //使用ThreadLocal绑定数据，
        UserHolder.set(user);
        return true;
    }
}
